<template>
  <div class="contanier" @click="cleanEdit">
    <div class="table-wrapper">
      <div class="table-row" v-for="(scope, row) in tableData" :key="row">
        <div
          class="table-column"
          v-for="(item, column) in changeColumns"
          :key="item.key"
        >
          <div
            :class="
              isForbidRows(row) || isForbidColumns(column)
                ? 'table-item forbid'
                : 'table-item'
            "
            @click.stop="handleClick(scope, item.key, row, column)"
            @mouseover="handleMouseOver(row, item.key)"
            @mouseleave="handleMouseLeave(row, item.key)"
          >
            <div
              v-if="
                editingRow === row &&
                item.key === editingColumn &&
                !(addRows && row == 0) &&
                !(addColumns && column == 0) &&
                !isForbidRows(row) &&
                !isForbidColumns(column)
              "
            >
              <!--  @input="handleInput($event, row, column)"  :maxlength="formartMaxLength(row,column)" -->
              <el-input
                class="input"
                v-model="scope[item.key]"
                :maxlength="formartMaxLength"
                @blur="finishEdit($event, row, column)"
              />
            </div>
            <div v-else>
              <div :class="row === 0 ? 'title' : 'content'">
                {{ scope[item.key] }}
              </div>
              <div
                v-if="
                  deleteRow === row &&
                  deleteColumn.length > 0 &&
                  deleteColumn === item.key &&
                  ((scope === tableData[0] && column !== 0) ||
                    (item.key === 'column0' && row !== 0)) &&
                  !(addRows && row == 0) &&
                  !(addColumns && column == 0)
                "
                class="el-icon-error delete"
                @click="
                  scope === tableData[0]
                    ? deleteColumns(column)
                    : deleteRows(row)
                "
              ></div>
            </div>
          </div>
        </div>
      </div>

      <!-- <div>
        <el-button
          class="el-icon-circle-plus"
          @click="addRow"
          v-if="addRows && limit > tableData.length"
        ></el-button>
      </div> -->

      <div
        style="margin-left: 10px; margin-top: 10px"
        @click="addRow"
        v-if="addRows && limit > tableData.length"
      >
        <svg
          t="1699458795843"
          class="icon"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="2666"
          width="32"
          height="32"
        >
          <path
            d="M276.8 59.6C112.6 144.7 0 315.5 0 513.2c0 459.6 560.3 681.9 876.6 353.6 404.3-419.2-98.5-1064.5-599.8-807.2zM794 512c0 28.1-22.8 50.9-50.9 50.9H562.9v180.2c0 28.1-22.8 50.9-50.9 50.9-28.1 0-50.9-22.8-50.9-50.9V562.9H280.9c-28.1 0-50.9-22.8-50.9-50.9 0-28.1 22.8-50.9 50.9-50.9h180.2V280.9c0-28.1 22.8-50.9 50.9-50.9 28.1 0 50.9 22.8 50.9 50.9v180.2h180.2c28.1 0 50.9 22.8 50.9 50.9z"
            fill="#999999"
            p-id="2667"
          ></path>
        </svg>
      </div>
    </div>

    <div
      style="margin-left: 10px; margin-top: 25px"
      @click="addColumn"
      v-if="addColumns && limit > changeColumns.length"
    >
      <svg
        t="1699458795843"
        class="icon"
        viewBox="0 0 1024 1024"
        version="1.1"
        xmlns="http://www.w3.org/2000/svg"
        p-id="2666"
        width="32"
        height="32"
      >
        <path
          d="M276.8 59.6C112.6 144.7 0 315.5 0 513.2c0 459.6 560.3 681.9 876.6 353.6 404.3-419.2-98.5-1064.5-599.8-807.2zM794 512c0 28.1-22.8 50.9-50.9 50.9H562.9v180.2c0 28.1-22.8 50.9-50.9 50.9-28.1 0-50.9-22.8-50.9-50.9V562.9H280.9c-28.1 0-50.9-22.8-50.9-50.9 0-28.1 22.8-50.9 50.9-50.9h180.2V280.9c0-28.1 22.8-50.9 50.9-50.9 28.1 0 50.9 22.8 50.9 50.9v180.2h180.2c28.1 0 50.9 22.8 50.9 50.9z"
          fill="#999999"
          p-id="2667"
        ></path>
      </svg>
    </div>
  </div>
</template>

<script>
export default {
  name: "customTable",
  props: {
    columns: {
      type: Array,
      default: () => [{ key: "column0" }],
    },
    rows: {
      type: Array,
      default: () => [{ column0: "" }],
    },
    rows1: {
      type: Array,
      default: () => [{ column0: "",column1: "",column2: "",column3: ""}],
    },
    
    addRows: {
      type: Boolean,
      default: false,
    },
    addColumns: {
      type: Boolean,
      default: false,
    },

    keyList: {
      type: Array,
      default: () => ["realmName", "realmValue"],
    },

    limit: {
      type: Number | String,
      default: 1000,
    },

    forbidRows: {
      type: Array,
      default: () => [10000],
    },

    forbidColumns: {
      type: Array,
      default: () => [10000],
    },
    rules: {
      type: Array,
      default: () => [
        { type: "TEXT", before: 5, after: 2, number: 100 },
        { type: "TEXT", before: 6, after: 2, number: 100 },
      ],
    },
    rowMaxLengths: {
      type: Array,
      default: () => [
        {row: 0, limit:10000},

      ],
    },
    columnMaxLengths: {
      type: Array,
      default: () => [
        {column: 0, limit:10000},
      ],
    },
  },
  data() {
    return {
      // 其他初始数据行
      tableData: this.rows,
      //缓存老数据
      newTableData:null,
      // 其他初始列
      changeColumns: this.columns,
      editingColumn: null,
      editingColumnNum: null,
      editingRow: null,
      editingModel: null,
      deleteColumn: "",
      deleteRow: -1,
    };
  },

  mounted() {
    this.newTableData = {...this.rows};

  },
  watch: {
    rows: {
      handler(newValue, oldValue) {
        this.tableData = newValue;
      },
      deep: true, // 监视对象或数组内部值的变化
    },

    columns: {
      handler(newValue, oldValue) {
        this.changeColumns = newValue;
      },
      deep: true, // 监视对象或数组内部值的变化
    },
  },
  computed: {
    //输出结果
    formartTableData() {
      if (this.addColumns) {
        return this.formartColumnData();
      }
      if (this.addRows) {
        return this.formartRowsData();
      }
      return this.tableData;
    },


    formartMaxLength() {
      const row = this.editingRow;
      const column = this.editingColumnNum;
      for (let index = 0; index < this.rowMaxLengths.length; index++) {
        const element = this.rowMaxLengths[index];
        if (element.row == row) {
          return element.limit
        }
      }

      for (let index = 0; index < this.columnMaxLengths.length; index++) {
        const element = this.columnMaxLengths[index];
        if (element.column == column) {
          return element.limit
        }
      }
      return 1000000
    }
   
  },
  methods: {
    addColumn() {
      let newKey = `column${this.changeColumns.length}`;
      this.changeColumns.push({
        key: newKey,
      });
      this.tableData.forEach((item) => {
        this.$set(item, newKey, "");
      });

      this.newTableData.forEach((item) => {
        item[newKey] = ""
      });
    },
    addRow() {
      let lastObj = this.tableData[this.tableData.length - 1]; // 创建一个新的空对象
      var newObj = {};
      var obj1 = {};
      let arr = Object.keys(lastObj);
      for (let index = 0; index < arr.length; index++) {
        const key = arr[index];
        console.log("key",key);
        newObj[key] = "";
        obj1[key] = "";
      }
      
      this.tableData.push(newObj);
      this.newTableData.push(obj1);
      
    },
    handleClick(scope, key,row,column) {
      if (this.editingModel && this.editingModel !== scope) {
        this.handleInput(this.editingModel[this.editingColumn],this.editingRow,this.editingColumnNum);
        this.editingColumn = null;
        this.editingRow = null;
        this.editingModel = null;
        this.editingColumnNum = null;
      }
      // row.isEdit = true;
      this.editingColumnNum = column
      this.editingColumn = key;
      this.editingRow = row;
      this.editingModel = scope;
    },
    handleMouseOver(index, key) {
      this.deleteColumn = key;
      this.deleteRow = index;
    },
    handleMouseLeave() {
      this.deleteColumn = "";
      this.deleteRow = -1;
    },
    finishEdit(event, row, column) {
      let value = event.target.value;
      this.handleInput(value,row,column);
      this.editingColumn = null;
      this.editingRow = null;
      this.editingModel = null;
      // this.$nextTick(() => {
      //   // 更新数据
      //   this.$set(value, key, value[key]);
      // });
    },
    cleanEdit() {
      this.editingColumn = null;
      this.editingRow = null;
      this.editingModel = null;
    },

    deleteColumns(index) {
      this.tableData.forEach((item) => {
        this.$delete(item, this.changeColumns[index].key);
      });

      this.newTableData.forEach((item) => {
        delete item[this.changeColumns[index].key]
      });
      this.changeColumns.splice(index, 1);
    },

    deleteRows(index) {
      this.tableData.splice(index, 1);
      this.newTableData.splice(index, 1);
    },

    formartColumnData() {
      let arr = [];
      for (let i = 0; i < this.changeColumns.length; i++) {
        const params = {};
        let key = this.changeColumns[i].key;
        for (let index = 0; index < this.keyList.length; index++) {
          let subKey = this.keyList[index];
          let item = this.tableData[index];
          params[subKey] = item[key];
        }
        arr.push(params);
      }

      arr.splice(0, 1);
      return arr;
    },

    formartRowsData() {
      let arr = [];
      for (let index = 0; index < this.tableData.length; index++) {
        const params = {};
        let item = this.tableData[index];
        for (let i = 0; i < this.changeColumns.length; i++) {
          let key = this.changeColumns[i].key;
          let subK = this.keyList[i];
          params[subK] = item[key];
        }
        arr.push(params);
      }

      arr.splice(0, 1);
      return arr;
    },
    //是否禁止输入
    isForbidRows(rows) {

     
      if (this.forbidRows.length == 0) {
        return false;
      }
      
      return this.forbidRows.includes(rows);
    },
    //是否禁止输入
    isForbidColumns(rows) {
      if (this.forbidColumns.length == 0) {
        return false;
      }
      return this.forbidColumns.includes(rows);
    },

    handleInput(value, row, column) {
      let reg;
      let a = "TEXT";
      let before = 100;
      let after = 100;
      let number = 10;
      // 
      if (this.addRows && column < this.rules.length) {
        
        a = this.rules[column].type;
        before = this.rules[column].before;
        after = this.rules[column].after;
        number = this.rules[column].number;
      } else if (this.addColumns && row < this.rules.length) {
        
        a = this.rules[row].type;
        before = this.rules[row].before;
        after = this.rules[row].after;
        number = this.rules[row].number;
      } 

      if (a === "TEXT") {
        // 输入为整数，最多number位
        if (value.length > before) {
          this.tableData[this.editingRow][this.editingColumn] = value.substring(
            0,
            before
          );
          // this.newTableData[this.editingRow][this.editingColumn] = value.substring(
          //   0,
          //   before
          // );
          
        }
      } else {
        if (a === "INTEGER") {
          // 输入为整数，最多number位
          reg = new RegExp("^\\d{1," + number + "}$");
        }
        if (a === "DECIMAL") {
          reg = new RegExp(
            "^(\\-)?\\d{1," + before + "}(\\.\\d{1," + after + "})?$"
          );
        }

        if (a === "IOD") {
          // 校验是否包含小数点 如果包含的情况下走整数、不包含的情况下走小数
          if (value.indexOf("\.") === -1) {
            // 不包含
            reg = new RegExp("^\\d{1," + number + "}$");
          } else {
            reg = new RegExp(
              "^(\\-)?\\d{1," + before + "}(\\.\\d{1," + after + "})$"
            );
          }
        }

        if (reg.test(value)) {
          console.log("符合标准");
          this.tableData[this.editingRow][this.editingColumn] = value;
          this.newTableData[this.editingRow][this.editingColumn] = value;
        } else {
          console.log("不符合标准");
          console.log("原始值",this.newTableData);
          // this.tableData[this.editingRow][this.editingColumn] = this.newTableData[this.editingRow][this.editingColumn];
          if (this.newTableData[this.editingRow][this.editingColumn] !== "") {
            this.tableData[this.editingRow][this.editingColumn] = this.newTableData[this.editingRow][this.editingColumn];
          } else {
            this.tableData[this.editingRow][this.editingColumn] = "";
          }
        }
      }
    },
  },
};
</script>

<style scoped lang="less">
.contanier {
  width: 100%;
  display: flex;
  .table-wrapper {
    // border: 1px solid #dddfe6;
    display: flex;
    flex-direction: column;

    .table-row {
      display: flex;
      flex-direction: row;
    }
    .table-column {
      display: flex;
    }

    .table-item {
      width: 180px;
      height: 80px;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      text-align: center;
      border: 1px solid #dddfe6;
      margin-left: -1px;
      margin-bottom: -1px;
      //
      .input {
        width: 120px;
      }

      .delete {
        position: absolute;
        right: 10px;
        top: 30px;
        width: 20px;
        height: 20px;
        // margin-left: 20px;
      }

      .title {
        font-size: 18px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 600;
        color: #292830;
        line-height: 22px;
        width: 100%;
        height: 100%;
        overflow: hidden;
      }

      .content {
        width: 160px;
        margin-left: 10px;
        margin-right: 10px;
        // line-height: 80px;
        overflow: hidden;
        word-wrap: break-word;
      }
    }

    .forbid {
      background-color: #f8f8ff;
    }
  }
}
</style>
